package com.ljy.farm.service.unit;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ljy.farm.service.user.UserService;
import com.ljy.farm.constants.BusinessConstants;
import com.ljy.farm.constants.ExceptionConstants;
import com.ljy.farm.datasource.entities.Material;
import com.ljy.farm.datasource.entities.Unit;
import com.ljy.farm.datasource.entities.UnitExample;
import com.ljy.farm.datasource.entities.User;
import com.ljy.farm.datasource.mappers.MaterialMapperEx;
import com.ljy.farm.datasource.mappers.UnitMapper;
import com.ljy.farm.datasource.mappers.UnitMapperEx;
import com.ljy.farm.exception.BusinessRunTimeException;
import com.ljy.farm.exception.JshException;
import com.ljy.farm.service.log.LogService;
import com.ljy.farm.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Service
public class UnitService {
    private Logger logger = LoggerFactory.getLogger(UnitService.class);

    @Resource
    private UnitMapper unitMapper;

    @Resource
    private UnitMapperEx unitMapperEx;
    @Resource
    private UserService userService;
    @Resource
    private LogService logService;
    @Resource
    private MaterialMapperEx materialMapperEx;

    public Unit getUnit(long id) throws Exception {
        Unit result = null;
        try {
            result = unitMapper.selectByPrimaryKey(id);
        } catch (Exception e) {
            JshException.readFail(logger, e);
        }
        return result;
    }

    public List<Unit> getUnit() throws Exception {
        UnitExample example = new UnitExample();
        example.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<Unit> list = null;
        try {
            list = unitMapper.selectByExample(example);
        } catch (Exception e) {
            JshException.readFail(logger, e);
        }
        return list;
    }

    public List<Unit> select(String name, int offset, int rows) throws Exception {
        List<Unit> list = null;
        try {
            list = unitMapperEx.selectByConditionUnit(name, offset, rows);
        } catch (Exception e) {
            JshException.readFail(logger, e);
        }
        return list;
    }

    public Long countUnit(String name) throws Exception {
        Long result = null;
        try {
            result = unitMapperEx.countsByUnit(name);
        } catch (Exception e) {
            JshException.readFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertUnit(String beanJson, HttpServletRequest request) throws Exception {
        Unit unit = JSONObject.parseObject(beanJson, Unit.class);
        int result = 0;
        try {
            result = unitMapper.insertSelective(unit);
            logService.insertLog("计量单位", BusinessConstants.LOG_OPERATION_TYPE_ADD, request);
        } catch (Exception e) {
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int updateUnit(String beanJson, Long id, HttpServletRequest request) throws Exception {
        Unit unit = JSONObject.parseObject(beanJson, Unit.class);
        unit.setId(id);
        int result = 0;
        try {
            result = unitMapper.updateByPrimaryKeySelective(unit);
            logService.insertLog("计量单位",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(id).toString(), request);
        } catch (Exception e) {
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int deleteUnit(Long id, HttpServletRequest request) throws Exception {
        int result = 0;
        try {
            result = unitMapper.deleteByPrimaryKey(id);
            logService.insertLog("计量单位",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_DELETE).append(id).toString(), request);
        } catch (Exception e) {
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteUnit(String ids, HttpServletRequest request) throws Exception {
        List<Long> idList = StringUtil.strToLongList(ids);
        UnitExample example = new UnitExample();
        example.createCriteria().andIdIn(idList);
        int result = 0;
        try {
            result = unitMapper.deleteByExample(example);
            logService.insertLog("计量单位", "批量删除,id集:" + ids, request);
        } catch (Exception e) {
            JshException.writeFail(logger, e);
        }
        return result;
    }

    public int checkIsNameExist(Long id, String name) throws Exception {
        UnitExample example = new UnitExample();
        example.createCriteria().andIdNotEqualTo(id).andUnameEqualTo(name).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<Unit> list = null;
        try {
            list = unitMapper.selectByExample(example);
        } catch (Exception e) {
            JshException.readFail(logger, e);
        }
        return list == null ? 0 : list.size();
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteUnitByIds(String ids) throws Exception {
        logService.insertLog("计量单位",
                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_DELETE).append(ids).toString(),
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
        User userInfo = userService.getCurrentUser();
        String[] idArray = ids.split(",");
        int result = 0;
        try {
            result = unitMapperEx.batchDeleteUnitByIds(new Date(), userInfo == null ? null : userInfo.getId(), idArray);
        } catch (Exception e) {
            JshException.writeFail(logger, e);
        }
        return result;
    }

    /**
     * create by: qiankunpingtai
     * website：https://qiankunpingtai.cn
     * description:
     * 正常删除，要考虑数据完整性，进行完整性校验
     * create time: 2019/4/11 10:20
     *
     * @return int
     * @Param: ids
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteUnitByIdsNormal(String ids) throws Exception {
        /**
         * 校验
         * 1、产品表	jsh_material
         * 是否有相关数据
         * */
        int deleteTotal = 0;
        if (StringUtils.isEmpty(ids)) {
            return deleteTotal;
        }
        String[] idArray = ids.split(",");
        /**
         * 校验产品表	jsh_material
         * */
        List<Material> materialList = null;
        try {
            materialList = materialMapperEx.getMaterialListByUnitIds(idArray);
        } catch (Exception e) {
            JshException.readFail(logger, e);
        }
        if (materialList != null && materialList.size() > 0) {
            logger.error("异常码[{}],异常提示[{}],参数,UnitIds[{}]",
                    ExceptionConstants.DELETE_FORCE_CONFIRM_CODE, ExceptionConstants.DELETE_FORCE_CONFIRM_MSG, ids);
            throw new BusinessRunTimeException(ExceptionConstants.DELETE_FORCE_CONFIRM_CODE,
                    ExceptionConstants.DELETE_FORCE_CONFIRM_MSG);
        }
        /**
         * 校验通过执行删除操作
         * */
        deleteTotal = batchDeleteUnitByIds(ids);
        return deleteTotal;
    }

    /**
     * 根据名称获取类型
     *
     * @param name
     */
    public Long getUnitIdByName(String name) {
        Long unitId = 0l;
        UnitExample example = new UnitExample();
        example.createCriteria().andUnameEqualTo(name).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<Unit> list = unitMapper.selectByExample(example);
        if (list != null && list.size() > 0) {
            unitId = list.get(0).getId();
        }
        return unitId;
    }
}
